package com.nageoffer.jobtrain.projects.config;

import io.minio.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * minio 工具配置类
 */
@Component
@RequiredArgsConstructor
public class MinioConfig {
    private final MinioClient minioClient;

    /**
     * minio项目桶名称
     */
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 上传文件至minio
     *
     * @param fileName    文件名
     * @param stream      输出流
     * @param contentType 文件类型
     * @return 上传文件信息得到 url
     */
    public String uploadFile(String fileName, InputStream stream, String contentType) throws Exception {
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        // 进行保存文件
        minioClient.putObject(PutObjectArgs.builder()
                .contentType(contentType)
                .stream(stream, -1, 10485760)
                .bucket(bucketName)
                .object(fileName)
                .build());
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .method(Method.GET)
                .build());
    }
}